package cn.silently9527.download;


import cn.silently9527.download.download.Downloader;
import cn.silently9527.download.download.MultiThreadFileDownloader;
import cn.silently9527.download.support.MultiThreadDownloadProgressPrinter;
import org.springframework.util.Assert;

import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;

public class FastDownloadApplication {


    public static void main(String[] args) throws IOException {
        int threadsNum = 1;
        String fileURL = "";
        String tartgetDir = "";

        if (args == null || args.length != 3) {
            error("请使用参数格式 xxx.exe  30[线程数>0]  url[正确的下载的资源]  dir[正确的存储路径]");
            return;
        } else {
            try {
                threadsNum = Integer.parseInt(args[0]);
                Assert.state(threadsNum > 0, "error");
                fileURL = args[1];
                tartgetDir = args[2];
                File dir = new File(tartgetDir);
                Assert.state(dir.exists() && dir.isDirectory(), "error");
            } catch (Exception exception) {
                error("请使用参数格式 xxx.exe  30[线程数>0]  url[正确的下载的资源]  dir[正确的存储路径]");
                return;
            }
        }

        try {
            MultiThreadDownloadProgressPrinter downloadProgressPrinter = new MultiThreadDownloadProgressPrinter(threadsNum);
            CompletableFuture.runAsync(() -> {
                while (true) {
                    long alreadyDownloadLength = downloadProgressPrinter.getAlreadyDownloadLength();
                    long contentLength = downloadProgressPrinter.getContentLength();
                    System.out.println(contentLength + "  =>  " + alreadyDownloadLength);
                    if (alreadyDownloadLength != 0 && alreadyDownloadLength >= contentLength) {
                        break;
                    }
                    try {
                        Thread.sleep(1000L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });

            Downloader downloader = new MultiThreadFileDownloader(threadsNum, downloadProgressPrinter);
            downloader.download(fileURL, tartgetDir);
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
            error("请使用参数格式 xxx.exe  30[线程数>0]  url[正确的下载的资源]  dir[正确的存储路径]");
        }
    }

    private static void error(String msg) {
        try {
            //windows
            JOptionPane.showMessageDialog(null,
                    msg,
                    "", JOptionPane.ERROR_MESSAGE);
        } catch (Exception exception) {
            //linux
            System.out.println(msg);
        }
    }

}
